<template>
    <div class="qilin-QilinQuillRichtext">
        <QuillEditor
            ref="QilinQuillRichtext"
            :content="ownQuillRichtextConfig.content"
            :contentType="ownQuillRichtextConfig.contentType || 'html' "
            :options="options"
            @blur="handleBlur"
            :style="ownQuillRichtextConfig.style || 'min-height:180px;' "
        ></QuillEditor>
    </div>
</template>

<script setup>
// import {uploadFiles} from "@/api/index.js";
// 引入插件
import {QuillEditor} from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";

// 接收来自父组件的传参
const propsValue=defineProps({
    quillRichtextConfig:{
        type:Object,
        default(){
            return {
                content:"", //显示内容
                contentType:"html", //希望展示的内容类型，官网文档默认为delta，这里默认为html
                placeholder:"请输入内容", //预展示内容
                enable:true, //是否可编辑，默认为true
                readOnly:false, //是否为只读模式，默认为false
                theme:"snow", //编辑器的主题模式，默认为snow，官方提供snow和bubble两个主题
                toolbar:"", //工具栏选项
                modules:"", //注册模块的选项
                options:"", //配置编辑器的选项
                globalOptions:"", //配置编辑器的全局选项-只有在全局注册QuillEDitor组件时才使用该配置项
                style:"" //自定义样式
            };
        }
    },
    content:{ //用以回显
        type:String,
        default:""
    }
});

// 暴露父组件的自定义方法
const emits=defineEmits(["update:quillRichtextConfig","success"]);

// 组件自身的配置项
let ownQuillRichtextConfig=computed({
    get(){
        propsValue.quillRichtextConfig.content=propsValue.content;
        return propsValue.quillRichtextConfig;
    },
    set(val){
        emits("update:quillRichtextConfig",val);
    }
});
// 获取元素DOM
let QilinQuillRichtext=ref(null);

// 上传图片事件处理
const handlers={
    image:function image(){
        let fileInput=document.body.querySelector("input.qilin-image[type=file]");
        if(fileInput === null){
            fileInput=document.createElement("input");
            fileInput.setAttribute("type","file");
            fileInput.setAttribute("accept","image/png,image/jpg,image/jpeg,image/gif");
            fileInput.classList.add("qilin-image");
            fileInput.addEventListener("change",function(){
                uploadImage(fileInput.files[0]);
            });
            document.body.appendChild(fileInput);
        };
        fileInput.click();
    }
};
// 自定义粘贴图片功能
const initPasteImage=()=>{
    let quill=QilinQuillRichtext.value.getQuill();
    quill.root.addEventListener("paste",(e)=>{
        if(e.clipboardData && e.clipboardData.files && e.clipboardData.files.length){
            e.preventDefault();
            [].forEach.call(e.clipboardData.files,(file)=>{
                if(!file.type.match(/^image\/(gif|jpe?g|png|bmp)/i)){
                    return;
                };
                uploadImage(file);
            });
        };
    });
};
// 上传图片至服务器事件监听
const uploadImage=(file)=>{
    let formData=new FormData();
    formData.append("file",file);
    uploadFiles(formData).then((res)=>{
        let quill=QilinQuillRichtext.value.getQuill();
        if(res.code === 200){
            // 获取光标所在位置
            let length=quill.getSelection().index;
            // 插入图片
            quill.insertEmbed(length,"image",res.data.url);
            // 调整光标位置到最后
            quill.setSelection(length+1);
        }else{
            ElMessage({
                message:res.msg || "系统错误",
                type:"error"
            });
        };
    });
};

// 富文本编辑器配置项
let options=reactive({
    placeholder:ownQuillRichtextConfig.value.placeholder || "请输入文本内容",
    theme:"snow",
    modules: { //编辑器包含的模块和各自的选项
        toolbar:{
            container:[
                ["bold", "italic", "underline", "strike"],       // 加粗 斜体 下划线 删除线
                ["blockquote", "code-block"],                    // 引用  代码块
                [{ list: "ordered" }, { list: "bullet" }],       // 有序、无序列表
                [{ indent: "-1" }, { indent: "+1" }],            // 缩进
                [{ size: ["small", false, "large", "huge"] }],   // 字体大小
                [{ header: [1, 2, 3, 4, 5, 6, false] }],         // 标题
                [{ color: [] }, { background: [] }],             // 字体颜色、字体背景颜色
                [{ align: [] }],                                 // 对齐方式
                ["clean"],                                       // 清除文本格式
                ["link", "image", "video"]                       // 链接、图片、视频
            ],
            handlers //监听选中图片事件
        }
    },
    formats: [ // 编辑器中允许的格式的白名单
        'header', 'bold', 'italic', 'underline', 'strike',
        'blockquote', 'code-block', 'list', 'bullet', 'indent',
        'link', 'image', 'color', 'background', 'font', 'size', 'align'
    ]
});


// 失去焦点事件监听
const handleBlur=(dom)=>{
    // console.log(QilinQuillRichtext.value.getContents());
    // console.log(QilinQuillRichtext.value.getEditor());
    // console.log(QilinQuillRichtext.value.getHTML());
    // console.log(QilinQuillRichtext.value.getQuill());
    // console.log(QilinQuillRichtext.value.getText());
    emits("success",QilinQuillRichtext.value.getHTML());
};

// 暴露子组件的自定义事件
defineExpose({
    handleBlur
});

// 声明周期逻辑区域
onMounted(()=>{
    initPasteImage();
});

</script>

<style lang="scss" scoped>
:deep(.ql-container){
    img{
        width:200px;
        height:200px;
        margin:0 5px 0 0;
    }
    .ql-tooltip[data-mode="link"]::before {
        content: "请输入链接地址:";
    }
    .ql-tooltip.ql-editing a.ql-action::after {
        border-right: 0px;
        content: "保存";
        padding-right: 0px;
    }

    .ql-tooltip[data-mode="video"] {
        left: 0 !important;
    }

    .ql-tooltip[data-mode="video"]::before {
        content: "请输入视频地址:";
    }
}
:deep(.ql-formats){
    line-height:24px;
    .ql-picker.ql-size .ql-picker-label::before,
    .ql-picker.ql-size .ql-picker-item::before {
        content: "14px";
    }

    .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
    .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
        content: "10px";
    }

    .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
    .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
        content: "18px";
    }

    .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
    .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
        content: "32px";
    }

    .ql-picker.ql-header .ql-picker-label::before,
    .ql-picker.ql-header .ql-picker-item::before {
        content: "文本";
    }

    .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
    .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
        content: "标题1";
    }

    .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
    .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
        content: "标题2";
    }

    .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
    .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
        content: "标题3";
    }

    .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
    .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
        content: "标题4";
    }

    .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
    .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
        content: "标题5";
    }

    .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
    .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
        content: "标题6";
    }

    .ql-picker.ql-font .ql-picker-label::before,
    .ql-picker.ql-font .ql-picker-item::before {
        content: "标准字体";
    }

    .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
    .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
        content: "衬线字体";
    }

    .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
    .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
        content: "等宽字体";
    }

}
</style>
<style lang="scss">
input.qilin-image{
    display:none;
}
</style>
